package com.sunfeng.netty.atguigu.linebasedframedecoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author sunfeng
 * @date 2021/05/19 11:25
 **/
@Slf4j
public class TimeClientHandler extends ChannelInboundHandlerAdapter {


    private int counter;

    private byte[] req;

    public TimeClientHandler() {
        req = ("NOW TIME IS NOW " + System.getProperty("line.separator")).getBytes();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       log.info("数据为：" + msg + "counter为：" + ++counter);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 100; i++) {
            ByteBuf byteBuf = Unpooled.copiedBuffer(req);
            ctx.writeAndFlush(byteBuf);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
        ctx.close();
    }
}
